<?php
/**
 * @title 24. 两两交换链表中的节点 - 迭代
 * @author start2004
 */

class ListNode {
    public $val = 0;
    public $next = null;
    function __construct($val) { $this->val = $val; }
}

class Solution {

    /**
     * @param ListNode $head
     * @return ListNode
     */
    function swapPairs($head) {
        /**
         * @since 2020-07-13 新增头节点, 避免while循环中的if($a === null)判断
         */
        $node = new ListNode(0);
        $node->next = $head;
        
        /**
         * @since 2020-07-03 交换b和c
         *
         *    ↓  ↓
         * a->b->c->d
         * a->c->b->d
         *       b->d->e->f
         *       A->B->C->D
         *             ↑  ↑
         *
         * 第2次交换d和e, b和d变成了新的A和B
         */
        $a = $node;
        $b = $node->next;
        while($b !==null AND $b->next !== null){
            /**
             * @since 2020-07-03 准备元素
             */
            $c = $b->next;
            $d = $c->next;

            /**
             * @since 2020-07-03 重新建立关系
             */
            $a->next = $c;
            $c->next = $b;
            $b->next = $d;

            /**
             * @since 2020-07-03 下次循环准备
             */
            // unset($a);
            $a = $b;
            $b = $d;
        }

        /**
         * @return
         */
        return $node->next;
    }
}




/**
 * @url http://127.0.0.1/leetcode/202007/20200703.php
 */
$arr = [1,2,3,4,5,6,7];
$node = new ListNode($arr[count($arr)-1]);
for($i=count($arr)-2; $i>=0; $i--){
    $next = $node;
    $node = new ListNode($arr[$i]);
    $node->next = $next;
}

$datas = [
    $node,
];

include_once dirname(__DIR__) . DIRECTORY_SEPARATOR ."xhprof.php";
$xhprof = new Xhprof();
foreach ($datas as $data){
    var_dump($data);

    $obj = new Solution();
    $result = $obj->swapPairs($data);
    print_r($result);
    echo str_repeat("<br>", 3);
}
$xhprof->end();
